//
// Created by BianZheng on 2021/12/31.
//

#include <string>
#include <vector>
#include <spdlog/spdlog.h>

#include "ConvertRatings.hpp"
#include "StringUtil.hpp"
#include "FileOut.hpp"

using namespace Rec2MIPS;

void ReadFile(const char *input_path, std::vector<RatingString> &rating_str_l) {
    const int file_size = 4;
    std::string itemID = "-1";

    const int report_every = 1000;
    for (int file_id = 1; file_id <= file_size; file_id++) {
        spdlog::info("read fileID {}", file_id);
        char input_fname[512];
        sprintf(input_fname, "%s/combined_data_%d.txt", input_path, file_id);
        std::ifstream in(input_fname);
        if (!in.is_open()) {
            spdlog::info("error, not open");
            exit(-1);
        }
        std::string line;
        while (getline(in, line)) // line中不包括每行的换行符
        {

            std::string flag;
            std::string::size_type position;
            //find 函数 返回jk 在s 中的下标位置
            position = line.find(':');
            if (position != line.npos)  // find
            {
                line = line.substr(0, line.length() - 1);
                //find
                itemID = line;
                if (std::stoi(line) % report_every == 0) {
                    spdlog::info("netflix current read itemID {}, total {}", std::stoi(line), 17700);
                }
            } else {
                std::vector<std::string> arr_str = Rec2MIPS::split(line, ',');
                std::string userID = arr_str[0];
                std::string rating = arr_str[1];
                rating_str_l.emplace_back(userID, itemID, rating);
            }

        }
        in.close();
    }
}

using namespace std;

int main(int argc, char **argv) {
    if (argc != 3) {
        spdlog::info("input path, output filename");
        return 0;
    }
    char *input_path = argv[1];
    char *output_fname = argv[2];
    spdlog::info("input path {}, output filename {}", input_path, output_fname);

    vector<RatingString> rating_str_l;
    ReadFile(input_path, rating_str_l);

    std::vector<RatingNum> rating_num_l;
    pair<int, int> data_stat = ConvertRatings(rating_str_l, rating_num_l);

    spdlog::info("Netflix total n_user {}, total n_item {}", data_stat.first, data_stat.second);

    WriteFile(output_fname, "Netflix", rating_num_l);
    return 0;
}